<template>
  <div class="bg-white rounded-lg shadow-sm">
    <div class="p-4 border-b border-gray-200">
      <div class="flex items-center justify-between">
        <h3 class="text-lg font-semibold text-gray-900">充电桩管理表格</h3>
        <div class="flex space-x-2">
          <el-button type="primary" size="small" @click="showAddModal = true">
            <el-icon><Plus /></el-icon>
            添加充电桩
          </el-button>
          <el-button
            type="danger"
            size="small"
            :disabled="!hasSelectedPiles"
            @click="handleBatchDelete"
          >
            <el-icon><Delete /></el-icon>
            批量删除
          </el-button>
          <el-button
            type="warning"
            size="small"
            :disabled="!hasSelectedPiles"
            @click="showBatchEditModal = true"
          >
            <el-icon><Edit /></el-icon>
            批量编辑
          </el-button>
        </div>
      </div>
    </div>

    <!-- 搜索和筛选 -->
    <div class="p-4 bg-gray-50 border-b border-gray-200">
      <div class="grid grid-cols-1 md:grid-cols-4 gap-4">
        <el-input
          v-model="searchQuery"
          placeholder="搜索充电桩ID或名称"
          clearable
          @input="handleSearch"
        >
          <template #prefix>
            <el-icon><Search /></el-icon>
          </template>
        </el-input>

        <el-select v-model="statusFilter" placeholder="筛选状态" clearable>
          <el-option label="全部状态" value="" />
          <el-option label="可用" value="available" />
          <el-option label="占用" value="occupied" />
          <el-option label="维护" value="maintenance" />
        </el-select>

        <el-select v-model="locationFilter" placeholder="筛选位置" clearable>
          <el-option label="全部位置" value="" />
          <el-option label="科技园A区" value="科技园A区停车场" />
          <el-option label="科技园B区" value="科技园B区停车场" />
          <el-option label="科技园C区" value="科技园C区停车场" />
          <el-option label="备用区" value="备用充电区" />
        </el-select>

        <el-button type="primary" @click="resetFilters">重置筛选</el-button>
      </div>
    </div>

    <el-table
      :data="filteredPiles"
      style="width: 100%"
      @selection-change="handleSelectionChange"
      max-height="600"
    >
      <el-table-column type="selection" width="55" />

      <el-table-column prop="id" label="充电桩ID" width="120" />

      <el-table-column prop="name" label="名称" width="150" />

      <el-table-column prop="location" label="位置" width="180" />

      <el-table-column prop="status" label="状态" width="100">
        <template #default="{ row }">
          <el-tag :type="getStatusTagType(row.status)" size="small">
            {{ getStatusText(row.status) }}
          </el-tag>
        </template>
      </el-table-column>

      <el-table-column prop="remainingPower" label="剩余功率" width="100">
        <template #default="{ row }">
          <span :class="getPowerColor(row.remainingPower, row.maxPower)">
            {{ row.remainingPower }}kW
          </span>
        </template>
      </el-table-column>

      <el-table-column prop="maxPower" label="最大功率" width="100">
        <template #default="{ row }">
          {{ row.maxPower }}kW
        </template>
      </el-table-column>

      <el-table-column prop="capacity" label="容量" width="100">
        <template #default="{ row }">
          {{ row.capacity }}kWh
        </template>
      </el-table-column>

      <el-table-column prop="canAccommodateVehicles" label="可承载车辆" width="120">
        <template #default="{ row }">
          <span class="font-medium">{{ row.canAccommodateVehicles }}辆</span>
        </template>
      </el-table-column>

      <el-table-column prop="predictedConfidence" label="预测可信度" width="120">
        <template #default="{ row }">
          <span :class="getConfidenceColor(row.predictedConfidence)">
            {{ row.predictedConfidence }}%
          </span>
        </template>
      </el-table-column>

      <el-table-column label="操作" width="200" fixed="right">
        <template #default="{ row }">
          <el-button type="primary" size="small" @click="handleView(row)">
            查看
          </el-button>
          <el-button type="warning" size="small" @click="handleEdit(row)">
            编辑
          </el-button>
          <el-button type="danger" size="small" @click="handleDelete(row)">
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 添加充电桩弹窗 -->
    <el-dialog v-model="showAddModal" title="添加充电桩" width="600px">
      <el-form :model="newPile" :rules="pileRules" ref="addFormRef" label-width="120px">
        <el-form-item label="充电桩ID" prop="id">
          <el-input v-model="newPile.id" placeholder="请输入充电桩ID" />
        </el-form-item>
        <el-form-item label="名称" prop="name">
          <el-input v-model="newPile.name" placeholder="请输入充电桩名称" />
        </el-form-item>
        <el-form-item label="位置" prop="location">
          <el-select v-model="newPile.location" placeholder="请选择位置">
            <el-option label="科技园A区停车场" value="科技园A区停车场" />
            <el-option label="科技园B区停车场" value="科技园B区停车场" />
            <el-option label="科技园C区停车场" value="科技园C区停车场" />
            <el-option label="备用充电区" value="备用充电区" />
          </el-select>
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-select v-model="newPile.status" placeholder="请选择状态">
            <el-option label="可用" value="available" />
            <el-option label="占用" value="occupied" />
            <el-option label="维护" value="maintenance" />
          </el-select>
        </el-form-item>
        <el-form-item label="剩余功率" prop="remainingPower">
          <el-input-number v-model="newPile.remainingPower" :min="0" :max="100" />
          <span class="ml-2 text-gray-500">kW</span>
        </el-form-item>
        <el-form-item label="最大功率" prop="maxPower">
          <el-input-number v-model="newPile.maxPower" :min="0" :max="100" />
          <span class="ml-2 text-gray-500">kW</span>
        </el-form-item>
        <el-form-item label="容量" prop="capacity">
          <el-input-number v-model="newPile.capacity" :min="0" :max="200" />
          <span class="ml-2 text-gray-500">kWh</span>
        </el-form-item>
        <el-form-item label="可承载车辆" prop="canAccommodateVehicles">
          <el-input-number v-model="newPile.canAccommodateVehicles" :min="0" :max="10" />
          <span class="ml-2 text-gray-500">辆</span>
        </el-form-item>
        <el-form-item label="预测可信度" prop="predictedConfidence">
          <el-input-number v-model="newPile.predictedConfidence" :min="0" :max="100" :precision="1" />
          <span class="ml-2 text-gray-500">%</span>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="flex justify-end space-x-2">
          <el-button @click="showAddModal = false">取消</el-button>
          <el-button type="primary" @click="handleAdd">确认添加</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 编辑充电桩弹窗 -->
    <el-dialog v-model="showEditModal" title="编辑充电桩" width="600px">
      <el-form :model="editPile" :rules="pileRules" ref="editFormRef" label-width="120px">
        <el-form-item label="充电桩ID" prop="id">
          <el-input v-model="editPile.id" disabled />
        </el-form-item>
        <el-form-item label="名称" prop="name">
          <el-input v-model="editPile.name" placeholder="请输入充电桩名称" />
        </el-form-item>
        <el-form-item label="位置" prop="location">
          <el-select v-model="editPile.location" placeholder="请选择位置">
            <el-option label="科技园A区停车场" value="科技园A区停车场" />
            <el-option label="科技园B区停车场" value="科技园B区停车场" />
            <el-option label="科技园C区停车场" value="科技园C区停车场" />
            <el-option label="备用充电区" value="备用充电区" />
          </el-select>
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-select v-model="editPile.status" placeholder="请选择状态">
            <el-option label="可用" value="available" />
            <el-option label="占用" value="occupied" />
            <el-option label="维护" value="maintenance" />
          </el-select>
        </el-form-item>
        <el-form-item label="剩余功率" prop="remainingPower">
          <el-input-number v-model="editPile.remainingPower" :min="0" :max="100" />
          <span class="ml-2 text-gray-500">kW</span>
        </el-form-item>
        <el-form-item label="最大功率" prop="maxPower">
          <el-input-number v-model="editPile.maxPower" :min="0" :max="100" />
          <span class="ml-2 text-gray-500">kW</span>
        </el-form-item>
        <el-form-item label="容量" prop="capacity">
          <el-input-number v-model="editPile.capacity" :min="0" :max="200" />
          <span class="ml-2 text-gray-500">kWh</span>
        </el-form-item>
        <el-form-item label="可承载车辆" prop="canAccommodateVehicles">
          <el-input-number v-model="editPile.canAccommodateVehicles" :min="0" :max="10" />
          <span class="ml-2 text-gray-500">辆</span>
        </el-form-item>
        <el-form-item label="预测可信度" prop="predictedConfidence">
          <el-input-number v-model="editPile.predictedConfidence" :min="0" :max="100" :precision="1" />
          <span class="ml-2 text-gray-500">%</span>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="flex justify-end space-x-2">
          <el-button @click="showEditModal = false">取消</el-button>
          <el-button type="primary" @click="handleUpdate">确认修改</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 批量编辑弹窗 -->
    <el-dialog v-model="showBatchEditModal" title="批量编辑" width="500px">
      <el-form :model="batchEditData" label-width="120px">
        <el-form-item label="状态">
          <el-select v-model="batchEditData.status" placeholder="请选择状态" clearable>
            <el-option label="可用" value="available" />
            <el-option label="占用" value="occupied" />
            <el-option label="维护" value="maintenance" />
          </el-select>
        </el-form-item>
        <el-form-item label="位置">
          <el-select v-model="batchEditData.location" placeholder="请选择位置" clearable>
            <el-option label="科技园A区停车场" value="科技园A区停车场" />
            <el-option label="科技园B区停车场" value="科技园B区停车场" />
            <el-option label="科技园C区停车场" value="科技园C区停车场" />
            <el-option label="备用充电区" value="备用充电区" />
          </el-select>
        </el-form-item>
      </el-form>
      <div class="mb-4 p-3 bg-blue-50 rounded-lg">
        <div class="text-sm text-blue-800">
          将对 {{ selectedPiles.length }} 个充电桩进行批量修改
        </div>
      </div>
      <template #footer>
        <div class="flex justify-end space-x-2">
          <el-button @click="showBatchEditModal = false">取消</el-button>
          <el-button type="primary" @click="handleBatchEdit">确认修改</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 查看详情弹窗 -->
    <el-dialog v-model="showViewModal" title="充电桩详情" width="600px">
      <div v-if="viewPile" class="space-y-4">
        <div class="grid grid-cols-2 gap-4">
          <div class="bg-gray-50 p-4 rounded-lg">
            <div class="text-sm text-gray-500 mb-1">充电桩ID</div>
            <div class="text-lg font-bold">{{ viewPile.id }}</div>
          </div>
          <div class="bg-gray-50 p-4 rounded-lg">
            <div class="text-sm text-gray-500 mb-1">名称</div>
            <div class="text-lg font-bold">{{ viewPile.name }}</div>
          </div>
          <div class="bg-gray-50 p-4 rounded-lg">
            <div class="text-sm text-gray-500 mb-1">位置</div>
            <div class="text-lg font-bold">{{ viewPile.location }}</div>
          </div>
          <div class="bg-gray-50 p-4 rounded-lg">
            <div class="text-sm text-gray-500 mb-1">状态</div>
            <el-tag :type="getStatusTagType(viewPile.status)">
              {{ getStatusText(viewPile.status) }}
            </el-tag>
          </div>
          <div class="bg-gray-50 p-4 rounded-lg">
            <div class="text-sm text-gray-500 mb-1">剩余功率</div>
            <div class="text-lg font-bold text-blue-600">{{ viewPile.remainingPower }}kW</div>
          </div>
          <div class="bg-gray-50 p-4 rounded-lg">
            <div class="text-sm text-gray-500 mb-1">最大功率</div>
            <div class="text-lg font-bold">{{ viewPile.maxPower }}kW</div>
          </div>
          <div class="bg-gray-50 p-4 rounded-lg">
            <div class="text-sm text-gray-500 mb-1">容量</div>
            <div class="text-lg font-bold">{{ viewPile.capacity }}kWh</div>
          </div>
          <div class="bg-gray-50 p-4 rounded-lg">
            <div class="text-sm text-gray-500 mb-1">可承载车辆</div>
            <div class="text-lg font-bold text-green-600">{{ viewPile.canAccommodateVehicles }}辆</div>
          </div>
        </div>
        <div class="bg-blue-50 p-4 rounded-lg">
          <div class="text-sm text-blue-600 mb-1">预测可信度</div>
          <div class="text-xl font-bold text-blue-800">{{ viewPile.predictedConfidence }}%</div>
          <div class="text-xs text-blue-500 mt-1">
            {{ viewPile.predictedConfidence >= 90 ? '预测精度高' : '数据量较少，预测精度一般' }}
          </div>
        </div>
      </div>
      <template #footer>
        <div class="flex justify-end">
          <el-button @click="showViewModal = false">关闭</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, computed } from 'vue'
import { useAppStore } from '@/stores'
import { Plus, Delete, Edit, Search } from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import type { ChargingPile } from '@/stores'

const store = useAppStore()

const showAddModal = ref(false)
const showEditModal = ref(false)
const showBatchEditModal = ref(false)
const showViewModal = ref(false)
const selectedPiles = ref<ChargingPile[]>([])
const searchQuery = ref('')
const statusFilter = ref('')
const locationFilter = ref('')

const newPile = ref({
  id: '',
  name: '',
  location: '',
  status: 'available' as 'available' | 'occupied' | 'maintenance',
  remainingPower: 50,
  maxPower: 60,
  capacity: 100,
  canAccommodateVehicles: 3,
  predictedConfidence: 90.0
})

const editPile = ref<ChargingPile>({} as ChargingPile)
const viewPile = ref<ChargingPile | null>(null)

const batchEditData = ref({
  status: '',
  location: ''
})

const pileRules = {
  id: [{ required: true, message: '请输入充电桩ID', trigger: 'blur' }],
  name: [{ required: true, message: '请输入充电桩名称', trigger: 'blur' }],
  location: [{ required: true, message: '请选择位置', trigger: 'change' }],
  status: [{ required: true, message: '请选择状态', trigger: 'change' }],
  remainingPower: [{ required: true, message: '请输入剩余功率', trigger: 'blur' }],
  maxPower: [{ required: true, message: '请输入最大功率', trigger: 'blur' }],
  capacity: [{ required: true, message: '请输入容量', trigger: 'blur' }],
  canAccommodateVehicles: [{ required: true, message: '请输入可承载车辆数', trigger: 'blur' }],
  predictedConfidence: [{ required: true, message: '请输入预测可信度', trigger: 'blur' }]
}

const filteredPiles = computed(() => {
  let piles = store.chargingPiles

  // 搜索过滤
  if (searchQuery.value) {
    const query = searchQuery.value.toLowerCase()
    piles = piles.filter(pile =>
      pile.id.toLowerCase().includes(query) ||
      pile.name.toLowerCase().includes(query)
    )
  }

  // 状态过滤
  if (statusFilter.value) {
    piles = piles.filter(pile => pile.status === statusFilter.value)
  }

  // 位置过滤
  if (locationFilter.value) {
    piles = piles.filter(pile => pile.location === locationFilter.value)
  }

  return piles
})

const hasSelectedPiles = computed(() => selectedPiles.value.length > 0)

const addFormRef = ref()
const editFormRef = ref()

const getStatusTagType = (status: string) => {
  switch (status) {
    case 'available': return 'success'
    case 'occupied': return 'danger'
    case 'maintenance': return 'warning'
    default: return 'info'
  }
}

const getStatusText = (status: string) => {
  switch (status) {
    case 'available': return '可用'
    case 'occupied': return '占用'
    case 'maintenance': return '维护'
    default: return '未知'
  }
}

const getPowerColor = (remaining: number, max: number) => {
  const ratio = remaining / max
  if (ratio > 0.6) return 'text-green-600'
  if (ratio > 0.3) return 'text-yellow-600'
  return 'text-red-600'
}

const getConfidenceColor = (confidence: number) => {
  if (confidence >= 90) return 'text-green-600'
  if (confidence >= 80) return 'text-yellow-600'
  return 'text-red-600'
}

const handleSearch = () => {
  // 搜索逻辑已在computed中处理
}

const resetFilters = () => {
  searchQuery.value = ''
  statusFilter.value = ''
  locationFilter.value = ''
}

const handleSelectionChange = (selection: ChargingPile[]) => {
  selectedPiles.value = selection
}

const handleView = (pile: ChargingPile) => {
  viewPile.value = pile
  showViewModal.value = true
}

const handleEdit = (pile: ChargingPile) => {
  editPile.value = { ...pile }
  showEditModal.value = true
}

const handleDelete = async (pile: ChargingPile) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除充电桩 ${pile.id} 吗？`,
      '确认删除',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )

    const index = store.chargingPiles.findIndex(p => p.id === pile.id)
    if (index !== -1) {
      store.chargingPiles.splice(index, 1)
    }
    ElMessage.success('删除成功')
  } catch {
    ElMessage.info('已取消删除')
  }
}

const handleAdd = async () => {
  try {
    await addFormRef.value.validate()

    store.chargingPiles.push({ ...newPile.value })
    showAddModal.value = false

    // 重置表单
    newPile.value = {
      id: '',
      name: '',
      location: '',
      status: 'available',
      remainingPower: 50,
      maxPower: 60,
      capacity: 100,
      canAccommodateVehicles: 3,
      predictedConfidence: 90.0
    }

    ElMessage.success('添加成功')
  } catch (error) {
    console.error('表单验证失败:', error)
  }
}

const handleUpdate = async () => {
  try {
    await editFormRef.value.validate()

    const index = store.chargingPiles.findIndex(p => p.id === editPile.value.id)
    if (index !== -1) {
      store.chargingPiles[index] = { ...editPile.value }
    }

    showEditModal.value = false
    ElMessage.success('修改成功')
  } catch (error) {
    console.error('表单验证失败:', error)
  }
}

const handleBatchDelete = async () => {
  try {
    await ElMessageBox.confirm(
      `确定要删除选中的 ${selectedPiles.value.length} 个充电桩吗？`,
      '确认批量删除',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )

    selectedPiles.value.forEach(pile => {
      const index = store.chargingPiles.findIndex(p => p.id === pile.id)
      if (index !== -1) {
        store.chargingPiles.splice(index, 1)
      }
    })

    selectedPiles.value = []
    ElMessage.success('批量删除成功')
  } catch {
    ElMessage.info('已取消删除')
  }
}

const handleBatchEdit = () => {
  const updates: Partial<ChargingPile> = {}

  if (batchEditData.value.status) {
    updates.status = batchEditData.value.status as 'available' | 'occupied' | 'maintenance'
  }

  if (batchEditData.value.location) {
    updates.location = batchEditData.value.location
  }

  selectedPiles.value.forEach(pile => {
    const index = store.chargingPiles.findIndex(p => p.id === pile.id)
    if (index !== -1) {
      store.chargingPiles[index] = { ...store.chargingPiles[index], ...updates }
    }
  })

  showBatchEditModal.value = false
  batchEditData.value = { status: '', location: '' }
  ElMessage.success(`已批量修改 ${selectedPiles.value.length} 个充电桩`)
}
</script>
</template>